# -*- coding:utf-8 -*-
__author__ = 'Serprutiy'


class cached_property(object):
    """
    Decorator that converts a method with a single self argument into a
    property cached on the instance.
    装饰器，将一个单参数的方法转换为实例中合适的缓存
    """
    def __init__(self, func):
        print('init cached_property')
        print(func)
        self.func = func

    def __get__(self, instance, type=None):
        print('__get__')
        print(instance)
        if instance is None:
            return self
        res = instance.__dict__[self.func.__name__] = self.func(instance)
        return res


class ConnectionRouter(object):
    def __init__(self, routers=None):
        """
        If routers is not specified, will default to settings.DATABASE_ROUTERS.
        如果routers没有指定，那么缺省从settings.DATABASE_ROUTERS中获取内容
        """
        # 这里在初始化时为，router = ConnectionRouter()，创建实例
        self._routers = routers

    @cached_property                    # 这里先是创建了一个cached_property的实例，记录routers为其中的func
    def routers(self):
        routers = [1, 2, 3]
        return routers

    def prints(self):
        print('test hello.')
        print(self.routers)             # self.routers的执行会调用到接口cached_property中的接口__get__

print('create obj')
router = ConnectionRouter()
router.prints()